package cn.lhl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

//适用于springboot2.7以前的
//@Configuration
//@EnableWebSecurity
public class WebSecurityConf extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 配置写死的内存用户
     */

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //写死内存
        auth.inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder.encode("123123")).authorities("admin")
                .and()
                .withUser("user").password(passwordEncoder.encode("123123")).authorities("comm")
        ;

        System.out.println("写死的:"+passwordEncoder.encode("123123"));
    }

    /**
     * 权限处理
     *
     * @param http
     * @throws Exception
     */
    protected void configure(HttpSecurity http) throws Exception {
        //写死的
        http.authorizeRequests()
                .antMatchers("/user/admin").hasAnyAuthority("admin")
                .antMatchers("user/comm").hasAnyAuthority("admin")
                .antMatchers("user/comm").hasAnyAuthority("comm")
                .antMatchers("/**").fullyAuthenticated()
                .anyRequest().authenticated()
                .and()
                .formLogin()
        ;
    }


    /**
     * 放行规则  放行不会走security过滤连
     *
     * @param web
     * @throws Exception
     */
    public void configure(WebSecurity web) throws Exception {
        //设置忽略的url
        web.ignoring().antMatchers("/hello");
        web.ignoring().antMatchers("/css/**", "/js/**");

    }

    /**
     * 密码加密类
     *
     * @return
     */

    //@Bean
    public PasswordEncoder passwordEncoder() {
        //不加密的
       // return NoOpPasswordEncoder.getInstance();
        //加密的
        return new BCryptPasswordEncoder();
    }


}
